package com.qbw.app.module.vehicle.popwindow;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;

import com.google.gson.Gson;
import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.lib.util.ScreenUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.VehiclePopwindowEventTypeFilterBinding;
import com.qbw.app.manager.GeneralManager;
import com.qbw.app.model.EventType;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.Warning;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.vehicle.adapter.VehicleAdapter;
import com.qbw.app.module.vehicle.holder.VehicleEventSubTypeHolder;
import com.qbw.core.base.BasePopupWindow;
import com.qbw.l.L;
import com.qbw.spm.P;

import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.request.impl.VehicleRequest.METHOD_EVENT_TYPE_LIST;

/**
 * @author QBW
 * @date 2019/9/3
 */
public class VehicleFilterPopWindow extends BasePopupWindow<VehiclePopwindowEventTypeFilterBinding> implements HttpTask.CallBack, VehicleEventSubTypeHolder.Listener {

    private Vehicle mVehicle;
    private List<EventType.SubEventType> mSelectedSubEventTypes;
    private VehicleAdapter mAdapter;

    private Listener mListener;

    private List<EventType.SubEventType> sPreSelectedSubEventTypes;

    public VehicleFilterPopWindow(Context context, Vehicle vehicle, Listener listener) {
        super(context, R.layout.vehicle_popwindow_event_type_filter);
        mVehicle = vehicle;
        mListener = listener;

    }

    @Override
    protected void init() {
        super.init();
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(mContext));
        mBinding.rcv.addItemDecoration(new InnerDecoration());
        mBinding.tvCancel.setOnClickListener(v -> dismiss());
        mBinding.tvOk.setOnClickListener(v -> {
            dismiss();
            sPreSelectedSubEventTypes = mSelectedSubEventTypes;
            if (mListener != null) {
                mListener.onSelectedEventTypes(mSelectedSubEventTypes);
            }
        });
        mAdapter = new VehicleAdapter(mContext, this);
        mBinding.rcv.setAdapter(mAdapter);
        mSelectedSubEventTypes = new ArrayList<>();
        Warning.ResponseList res = null;
        try {
            res = new Gson().fromJson(P.getString(Constant.KEY_EVENT_TYPE_CONFIG),
                                      Warning.ResponseList.class);
        } catch (Exception e) {
            e.printStackTrace();
            L.GL.e(e);
        }
        if (res == null) {
            GeneralManager.getInstance()
                          .getRequestManager()
                          .getVehicleRequest()
                          .getAlarmConfig(mVehicle != null ? mVehicle.getVehicleCode() : "", this)
                          .execute();
        } else {
            dealEventTypeConfig(res);
        }
    }

    private void dealEventTypeConfig(Warning.ResponseList res) {
        if (res.size() > 0) {
            EventType etEvent = new EventType();
            etEvent.setSubEventTypes(new ArrayList<>());
            EventType etElectricArea = new EventType();
            etElectricArea.setSubEventTypes(new ArrayList<>());
            EventType.SubEventType eventType;
            for (Warning w : res.getData()) {
                if (w.getQueryType() == Warning.QUERY_TYPE_EVENT) {
                    etEvent.getSubEventTypes()
                           .add(eventType = new EventType.SubEventType(w.getAlarmId(),
                                                                       w.getAlarmName()));
                    eventType.setSelected(isSubEventInPreSelectedSubEvents(eventType));
                    if (eventType.isSelected()) {
                        mSelectedSubEventTypes.add(eventType);
                    }
                } else if (w.getQueryType() == Warning.QUERY_TYPE_ELECTRIC_AREA) {
                    etElectricArea.getSubEventTypes()
                                  .add(eventType = new EventType.SubEventType(w.getAlarmId(),
                                                                              w.getAlarmName()));
                    eventType.setSelected(isSubEventInPreSelectedSubEvents(eventType));
                    if (eventType.isSelected()) {
                        mSelectedSubEventTypes.add(eventType);
                    }
                }
            }
            if (etEvent.getSubEventTypes().size() > 0) {
                etEvent.setEventName(ResUtil.getString(R.string.event_warning));
                //mSelectedSubEventTypes.addAll(etEvent.getSubEventTypes());
                mAdapter.addChild(etEvent);
            }
            if (etElectricArea.getSubEventTypes().size() > 0) {
                etElectricArea.setEventName(ResUtil.getString(R.string.electric_area));
                //mSelectedSubEventTypes.addAll(etElectricArea.getSubEventTypes());
                mAdapter.addChild(etElectricArea);
            }
        }
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        String method = httpTask.getMethod();
        if (method.equals(METHOD_EVENT_TYPE_LIST)) {
            /*EventType.Response response = (EventType.Response) entity;
            EventType.Data data = response.getData();
            VehicleAdapter adapter = new VehicleAdapter(mContext, this);
            adapter.addChild(data.getList());
            mBinding.rcv.setAdapter(adapter);*/
            Warning.ResponseList res = (Warning.ResponseList) entity;
            dealEventTypeConfig(res);
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        message = HttpRequestUtil.getMessage(errorCode, message);
        UniversalToastUtil.showFailedIconToast(message);
    }

    @Override
    public void onSelectEventSubTypeChanged(EventType.SubEventType type) {
        if (type.isSelected()) {
            mSelectedSubEventTypes.add(type);
        } else {
            mSelectedSubEventTypes.remove(type);
        }
        mBinding.tvOk.setEnabled(!mSelectedSubEventTypes.isEmpty());
    }

    private boolean isSubEventInPreSelectedSubEvents(EventType.SubEventType eventType) {
        if (sPreSelectedSubEventTypes == null) {
            return true;
        }
        int preSize = sPreSelectedSubEventTypes.size();
        if (preSize <= 0) {
            return false;
        }
        boolean b = false;
        for (EventType.SubEventType et : sPreSelectedSubEventTypes) {
            if (et.getEventId() == eventType.getEventId()) {
                b = true;
                break;
            }
        }
        return b;
    }

    private void initData(VehicleAdapter adapter) {




        /*EventType eventType = new EventType();
        eventType.setEventName("事件告警");
        List<EventType.SubEventType> eventSubTypes = new ArrayList<>();
        eventType.setSubEventTypes(eventSubTypes);

        EventType.SubEventType subEventType = new EventType.SubEventType();
        subEventType.setEventName("熄火后震动");
        subEventType.setEventId(EVENT_SHOCK_AFTER_STALLING);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("疑似碰撞");
        subEventType.setEventId(EVENT_POSSIBLE_CRASH);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("疑似翻车");
        subEventType.setEventId(EVENT_POSSIBLE_ROLLOVER);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("设备拔出");
        subEventType.setEventId(EVENT_DEVICE_OUT);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("非法位移");
        subEventType.setEventId(EVENT_ILLEGAL_MOVE);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName(mContext.getResources().getString(R.string.increase_speed_quick));
        subEventType.setEventId(EVENT_INCREASE_SPEED);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName(mContext.getResources().getString(R.string.reduce_speed_quick));
        subEventType.setEventId(EVENT_REDUCE_SPEED);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName(mContext.getResources().getString(R.string.turn_quick));
        subEventType.setEventId(EVENT_TURN_HURRY);
        eventSubTypes.add(subEventType);

        mSelectedSubEventTypes.addAll(eventType.getSubEventTypes());
        adapter.addChild(eventType);

        eventType = new EventType();
        eventType.setEventName("电子围栏");
        eventSubTypes = new ArrayList<>();
        eventType.setSubEventTypes(eventSubTypes);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("驶入电子围栏");
        subEventType.setEventId(EVENT_ELEC_AREA_IN);
        eventSubTypes.add(subEventType);

        subEventType = new EventType.SubEventType();
        subEventType.setEventName("驶出电子围栏");
        subEventType.setEventId(EVENT_ELEC_AREA_OUT);
        eventSubTypes.add(subEventType);

        mSelectedSubEventTypes.addAll(eventType.getSubEventTypes());
        adapter.addChild(eventType);*/
    }

    public interface Listener {
        void onSelectedEventTypes(List<EventType.SubEventType> subEventTypes);
    }

    private static class InnerDecoration extends RecyclerView.ItemDecoration {

        private Context mContext = XApplication.getInstance();
        private int mSpace15;
        private Paint mPaint;

        public InnerDecoration() {
            mPaint = new Paint();
            mPaint.setColor(Color.parseColor("#3B474C"));
            mSpace15 = ScreenUtil.dp2px(mContext, 15);
        }

        @Override
        public void onDrawOver(@NonNull Canvas c,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {
            super.onDrawOver(c, parent, state);
            int cc = parent.getChildCount();
            View view;
            for (int i = 0; i < cc; i++) {
                view = parent.getChildAt(i);
                c.drawRect(view.getLeft() + mSpace15,
                           view.getBottom() - 1,
                           view.getRight() - mSpace15,
                           view.getBottom(),
                           mPaint);
            }
        }
    }

}
